<template>
  <div class="bw-custom-com-attr-set">
    <component
      :is="curCom"
      :value="curNodeArrts"
      :comPropList="curCurtomComPropList"
      :nodeForList="curNodeForVarNamepList"
      @update:value="onUpdateValue"
    />
  </div>
</template>

<script lang="ts">
import { ref, unref, computed, markRaw, watch, defineComponent } from 'vue'
import {
  designUtils,
  useComDesignStoreWithOut,
  getCustomComDesignInfo,
} from '@/store'
import { getInsBwUtils } from '../../../../../content/create/utils/setupLogic/index'

import {
  createInsCom,
  BwCustomComFrontTypeEnum,
  type BwGetCustomComInfoFun,
  type BwCustomComDesignInfoModel,
  type BwCustomComNodeAttrModel,
} from '@bitwit/base-com-render'

export default defineComponent({
  name: 'BwCustomComAttrSet',
  setup() {
    const designStore = useComDesignStoreWithOut()

    const curCom = ref<any>(null)
    const curComCode = ref<string>('')
    const curComAppCode = ref<string>('')
    const curNodeArrts = ref<Record<string, BwCustomComNodeAttrModel>>({})

    /** 当前自定义组件外放属性列表 */
    const curCurtomComPropList = computed(() => {
      const list: Array<Record<string, string>> = []
      const designInfo = designStore.curDesignInfo
      const comProps = designInfo?.comProps

      if (Array.isArray(comProps) && comProps.length) {
        comProps.forEach((item) => {
          list.push({ label: item.name ?? '', value: item.key })
        })
      }
      return list
    })

    const extendBwUtils = computed(() => {
      const utils = getInsBwUtils({ params: {} })
      return utils
    })

    /** 当前自定义组件节点循环变量列表 */
    const curNodeForVarNamepList = computed(() => {
      const list: Array<any> = []
      const struct = designStore.getStructList
      const curNodeInfo = designStore.selectNodeEle

      let nodeId = curNodeInfo?.nodeId ?? null
      while (!!nodeId) {
        const nodeInfo = designUtils.findDomNodeInfo(struct, nodeId)?.node
        if (nodeInfo) {
          if (nodeInfo?.nodeForInfo?.visible) {
            list.push(
              {
                value: `${nodeInfo.nodeId}&index`,
                label: `${nodeInfo.nodeName}-循环下标`,
              },
              {
                value: `${nodeInfo.nodeId}&data`,
                label: `${nodeInfo.nodeName}-循环数据`,
              }
            )
          }

          nodeId = nodeInfo.parentNodeId
        } else {
          nodeId = null
        }
      }

      return list
    })

    const onUpdateValue = (data: Record<string, BwCustomComNodeAttrModel>) => {
      const curNode = designStore.selectNodeEle
      if (
        curNode &&
        JSON.stringify(curNodeArrts.value) != JSON.stringify(data)
      ) {
        console.log('onUpdateValue', data)

        const nodeId = curNode.nodeId
        designStore.onChangeNodeEleAttrs(nodeId, data)
      }
    }

    const initInsCom = (comAppCode, comCode) => {
      if (
        unref(curComAppCode) !== comAppCode ||
        unref(curComCode) !== comCode
      ) {
        curComCode.value = comCode
        curComAppCode.value = comAppCode
        getCustomComDesignInfo(comAppCode, comCode).then((res) => {
          const config = res?.comPropsSetConfig ?? {}
          const { appCode, comCode } = config

          if (appCode && comCode) {
            getCustomComDesignInfo(appCode, comCode).then((res) => {
              createInsCom(
                res as BwCustomComDesignInfoModel,
                BwCustomComFrontTypeEnum.pc,
                getCustomComDesignInfo as BwGetCustomComInfoFun,
                unref(extendBwUtils)
              ).then((insCom: any) => {
                curCom.value = markRaw(insCom)
              })
            })
          }
        })
      }
    }

    watch(
      () => designStore.selectNodeEle,
      (newVal) => {
        const { comAppCode, comName, attrs } = newVal ?? {}
        if (comAppCode && comName) {
          curNodeArrts.value = attrs ?? {}
          initInsCom(comAppCode, comName)
        }
      },
      { deep: true, immediate: true }
    )

    return {
      curCom,
      curNodeArrts,
      curCurtomComPropList,
      curNodeForVarNamepList,

      onUpdateValue,
    }
  },
})
</script>

<style lang="less" scoped>
.bw-custom-com-attr-set {
  padding: 8px;
  width: calc(100% - 16px);
}
</style>
